package com.hancher.gamelife2.picturecombine;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.GlideEngine;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.PathUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.base.BaseApplication;
import com.hancher.common.base.BaseFragment;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.rv.PageRecyclerViewManager;
import com.hancher.gamelife2.databinding.FragmentPictureCombineBinding;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.warkiz.widget.IndicatorSeekBar;
import com.warkiz.widget.OnSeekChangeListener;
import com.warkiz.widget.SeekParams;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * 描述 : 图片拼接 <br/>
 * 时间 : 2024/5/28 8:50 <br/>
 * 作者 : Hancher ytu_shaoweijie@163.com
 */
public class PictureCombineFragment extends BaseFragment<FragmentPictureCombineBinding> {

    private PageRecyclerViewManager<PictureCombineAdapter.ImageSelectItem> prvm;

    @Override
    protected void initView(Bundle savedInstanceState) {
        prvm = new PageRecyclerViewManager<PictureCombineAdapter.ImageSelectItem>()
                .setContext(getContext())
                .setRecyclerView(binding.rvImagesSelect)
                .setAdapter(new PictureCombineAdapter())
                .setCol(4)
                .init();
        binding.rvImagesSelect.setLongPressDragEnabled(true);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initListener() {

        // 图片选择
        binding.btnCaptureVideoPicture.setOnClickListener(v -> {
            PictureSelector.create(getContext())
                    .openGallery(SelectMimeType.ofImage())
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .setMaxSelectNum(30)
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            if (EmptyUtil.isEmpty(result)) {
                                ToastUtil.showErr("选择文件失败!");
                                return;
                            }
                            LogUtil.o(result);
                            List<PictureCombineAdapter.ImageSelectItem> result2 = new ArrayList<>();
                            for (LocalMedia localMedia : result) {
                                PictureCombineAdapter.ImageSelectItem item = new PictureCombineAdapter.ImageSelectItem(localMedia.getRealPath(), true);
                                result2.add(item);
                            }
                            prvm.freshData(result2);
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
        });

        // 4 图片拖拽
        binding.rvImagesSelect.setOnItemMoveListener(new OnItemMoveListener() {
            @Override
            public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
                int fromPosition = srcHolder.getAbsoluteAdapterPosition();
                int toPosition = targetHolder.getAbsoluteAdapterPosition();
                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(prvm.getRvList(), i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(prvm.getRvList(), i, i - 1);
                    }
                }
                prvm.getAdapter().notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {

            }
        });
        // 全选
        binding.btnSelectAll.setOnClickListener(v -> {
            if (prvm.getRvList() == null || prvm.getRvList().size() == 0) {
                return;
            }
            boolean nextSelect = !prvm.getRvList().get(0).isSelect();
            for (PictureCombineAdapter.ImageSelectItem item : prvm.getRvList()) {
                item.setSelect(nextSelect);
            }
            prvm.freshData();
        });
        // 反选
        binding.btnSelectRevert.setOnClickListener(v -> {
            if (prvm.getRvList() == null || prvm.getRvList().size() == 0) {
                return;
            }
            LogUtil.d("点击反选");
            for (PictureCombineAdapter.ImageSelectItem item : prvm.getRvList()) {
                item.setSelect(!item.isSelect());
            }
            prvm.freshData();
        });

        // 6 组合图片
        binding.btnCombination.setOnClickListener(v -> {
            WaitDialog waitDialog = WaitDialog.show("正在合成图片，请稍后");
            List<File> files = new ArrayList<>();
            for (PictureCombineAdapter.ImageSelectItem item : prvm.getRvList()) {
                if (item.isSelect()) {
                    files.add(new File(item.getImgPath()));
                }
            }
            LogUtil.d("图片拼接个数%d", files.size());
            int widthCount = Integer.parseInt(binding.editWeight.getEditableText().toString());
            // 组合图片
            AsyncUtils.run(emitter -> {

                File dir = new File(PathUtil.OUT_PUBLIC_DOWNLOAD, "VideoCombination");
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir.getAbsolutePath(), System.currentTimeMillis() + ".jpg");
                boolean result = PictureCombineUtil.combinePicture(files, widthCount, binding.seekbar.getProgress(), file);
                if (!result) {
                    emitter.onNext("");
                    emitter.onComplete();
                    return;
                }
                Uri uri = Uri.fromFile(file);
                BaseApplication.getInstance().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                emitter.onNext(file.getAbsolutePath());
                emitter.onComplete();
            }, (Consumer<String>) s -> {
                waitDialog.doDismiss();
                if (EmptyUtil.isEmpty(s)) {
                    ToastUtil.show("内存不足以拼接此图片");
                    return;
                }
                // 更新合成图片
                BigDecimal fileSize = BigDecimal.valueOf(new File(s).length());
                fileSize = fileSize.divide(BigDecimal.valueOf(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP);
                binding.txtCombination.setText("6. 生成路径：" + s + ", 大小:" + fileSize + "M");
                Glide.with(getContext()).load(new File(s)).into(binding.imgCombined);
            }, ToastUtil::showErr);
        });

        binding.seekbar.setOnSeekChangeListener(new OnSeekChangeListener() {
            @Override
            public void onSeeking(SeekParams seekParams) {

            }

            @Override
            public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
                binding.txtCombinationSize.setText("6. 长宽缩小倍数：" + seekBar.getProgress() + "%");
            }
        });
    }

}